package com.example.administrator.myview.http;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.util.List;

/**
 * HttpClient
 * Created by Administrator on 2017/12/5.
 */

public class HttpClient {

    //get请求
    private String get(String url){
        DefaultHttpClient client;
        HttpGet request;
        try {
            client= new DefaultHttpClient();
            request=new HttpGet(url);
            HttpResponse response=client.execute(request);
            if(response.getStatusLine().getStatusCode()== HttpStatus.SC_OK){
                String result=EntityUtils.toString(response.getEntity(),"UTF-8");
                return result;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return  null;
    }


    // POST请求
    private String post(String url,List<NameValuePair> params){
        DefaultHttpClient client=null;
        HttpPost request=null;
        try {
            client=new DefaultHttpClient();
            request=new HttpPost(url);
            request.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
            HttpResponse response=client.execute(request);
            if(response.getStatusLine().getStatusCode()== HttpStatus.SC_OK){
                String result= EntityUtils.toString(response.getEntity(),"UTF-8");
                return result;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return  null;
    }
}
